package com.sinodata.bsm.cicp.collector.sqlserver;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.AbstractJDBCCollector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.DBConnectionUtil;
import com.sinodata.bsm.common.constants.SeparatorConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

public class CPU extends AbstractJDBCCollector {
    private static final Logger logger = Logger.getLogger(CPU.class);

    //    private static final int DEADLOCK_WAIT_TIME = 60;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {

        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();

        try {

            String[] propMetas = getPropMeta();
            //        String serverName = this.getParamMap().get("服务器名");
            String serverName = this.getParamMap().get("ServerName");

            String sql = "sp_monitor";
            String[] rs = this.getStrings(serverName, sql, ip);

            ResPropertyValue propertyValueX = new ResPropertyValue();
            ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
            for (int i = 0; i < propMetas.length; i++) {
                propValues[i] = ResPropertyValue.createPropValue(rs[i], propMetas[i]);
            }

            propertyValueX.setValues(propValues);
            values.add(propertyValueX);

        } catch (Exception e) {
            logger.error("failed to collect sqlserver CPU", e);
            throw new CollectorException(e);
        }
        return values;
    }

    private String[] getStrings(String serverName, String sql, String ip) throws CollectorException {
        String[] propValArr = new String[1];
        Connection conn = null;
        ResultSet rst = null;
        Statement statement = null;
        try {//不调用getCachedResultSet 返回多个结果集合
            conn = DBConnectionUtil.getInstance().getConnection("sqlserver", ip, serverName);
            statement = conn.createStatement();
            rst = statement.executeQuery(sql);
            String cpuTime = null;
            while (rst != null) {
                while (rst.next()) {
                    String temp = rst.getString(1);
                    if (temp.indexOf("(") != -1) {
                        cpuTime = temp.substring(0, temp.indexOf("("));
                        break;
                    }
                }
                propValArr[0] = cpuTime;
                if (cpuTime != null) {
                    break;
                }
                if (statement.getMoreResults()) {
                    rst = statement.getResultSet();
                } else {
                    break;
                }
            }
        } catch (Exception ex) {
            logger.error("while connect database ", ex);
            throw new CollectorException(ex);
        } finally {

            if (rst != null) {
                try {
                    rst.close();
                } catch (SQLException e) {
                    logger.error("failed to close result set", e);
                    throw new CollectorException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    logger.error("failed to close statement", e);
                    throw new CollectorException(e);
                }
            }
            DBConnectionUtil.getInstance().returnConnection(conn);
        }
        return propValArr;
    }

    @SuppressWarnings("unused")
    private String getTabLineStr(ResultSet rst, int colNum) throws CollectorException {
        StringBuffer tabLineStr = new StringBuffer();
        try {
            for (int i = 1; i <= colNum; i++) {
                String val = rst.getString(i);
                if (val == null || val.trim().length() == 0) {
                    val = " ";
                } else
                    val = val.trim();
                tabLineStr.append(val).append(SeparatorConstants.COL_SEPARATOR);
            }
        } catch (Exception e) {
            logger.error("failed to get TabLineStr ", e);
            throw new CollectorException(e);
        }
        return tabLineStr.toString();
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "ServerName" };
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "CPUOccupancyTime" };
    }

}
